<?php

namespace App\HttpController\Admin;

use App\Common\Session;
use EasySwoole\ORM\DbManager;
use EasySwoole\Session\Context;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Http\AbstractInterface\Controller;

use App\Common\Tools;
use App\Model\User\User;

class Login extends Controller
{
    /**
     * @description: 登录
     * @param {*}
     * @return {*}
     */
    public function Login()
    {
        $param = $this->request()->getRequestParam();
        $user = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $model = User::invoke($client);
            return $model->scopWhere()->where('username', $param['username'])->get();
        });
        if (!$user) {
            Tools::json($this->response(), 500, [], '用户不存在');
        } elseif (!password_verify($param['password'], $user['password'])) {
            Tools::json($this->response(), 500, [], '用户或密码错误');
        } else {
            DbManager::getInstance()->invoke(function ($client) use ($user) {
                $model = User::invoke($client);
                $data  = [
                    'last_login' => date('Y-m-d H:i:s'),
                    'last_logip' => Tools::clientRealIP($this->request()),
                ];
                return $model->modifyData($user['id'], $data);
            });
            $user = $user->toArray();
            unset($user['password']);
            $expire = Config::getInstance()->getConf('SESSION.expire');
            if ($expire == 'never') {
                $user['expire'] = $expire;
            } else {
                $user['expire'] = time() + $expire;
            }
            $this->session()->set('adminUser', $user);
            Tools::json($this->response(), 200, ['user' => $user], '登录成功');
        }
    }

    // 封装session方法
    protected function session(): ?Context
    {
        $sessionName = Config::getInstance()->getConf('SESSION.name');
        // 封装一个方法，方便我们快速获取 session context
        $sessionId = $this->request()->getAttribute($sessionName);
        return Session::getInstance()->create($sessionId);
    }
}
